﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Routing;
using Norm;
using NormActiveRecord;

namespace Kazuku.Core.Models {
	public class KazukuContext : ActiveRecordEntity<KazukuContext> {
		public bool PageBuildingIsInProgress { get; set; }
		public Organization Org { get; set; }
		public Site Site { get; set; }
		public Page Page { get; set; }
		public PageModule RequestedPageModule { get; set; }
		public ObjectId PageID { get; set; }

		public KazukuContext(IModelFactory modelFactory) : base(modelFactory) { }
		
		public KazukuContext ByOrgCode(string orgCode) {
			KazukuContext context = Model.New<KazukuContext>();
			context.Org = Model.Single<Organization>(o => o.Code.ToLower() == orgCode.ToLower());
			context.Site = Model.Single<Site>(s => s.OrgCode.ToLower() == orgCode.ToLower());
			
			if (context.Org == null) {
				throw new Exception("Org not found for OrgCode=" + orgCode);
			}
			if (context.Site == null) {
				throw new Exception("Site not found for OrgCode=" + orgCode);
			}
			return context;
		}

		public void GetPageModuleFromRequest(RequestContext requestContext) {
			string moduleName = requestContext.RouteData.Values.ContainsKey("area") ? requestContext.RouteData.Values["area"].ToString() : string.Empty;	// Area and Module are currently synonymous.

			if (!string.IsNullOrEmpty(moduleName)) {
				string controller = requestContext.RouteData.Values["controller"].ToString();
				string action = requestContext.RouteData.Values["action"].ToString();
				
				RequestedPageModule = Model.New<PageModule>();
				RequestedPageModule.Area = moduleName;
				RequestedPageModule.Controller = controller;
				RequestedPageModule.Action = action;

				foreach (string key in requestContext.RouteData.Values.Keys) {
					RequestedPageModule.Parameters.Add(key, requestContext.RouteData.Values[key].ToString());
				}
			}
		}
	}
}
